package Servlets;

import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketServlet;

public class Wsservlet extends WebSocketServlet
{
	private static final long serialVersionUID = 1L;

	private final Set<ChatWebSocket>  _members = new CopyOnWriteArraySet<ChatWebSocket>();
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException ,IOException 
    {
        //getServletContext().getNamedDispatcher("default").forward(request,response);
    	response.getWriter().println("regular doGet()");
    }
    
    protected WebSocket doWebSocketConnect(HttpServletRequest request, String protocol)
    {
        return new ChatWebSocket();
    }

    
    class ChatWebSocket implements WebSocket
    {
        Outbound _outbound;
        String _name = "";
        
        public void onConnect(Outbound outbound)
        {
            _outbound=outbound;
            _members.add(this);
            System.out.println("Connected");
            System.out.println("Is open: " + this._outbound.isOpen());
        }
        
        public void onMessage(byte frame, byte[] data,int offset, int length)
        {}

        public void onMessage(byte frame, String data)
        {
        	
        	System.out.println("Received: " + data);
        	
			//Save name
			if(data.startsWith("name")){
        		_name=data.substring(5);
        		System.out.println("Register name: " + _name);
        		try {
					this._outbound.sendMessage(frame,"Connected");
					SendConnectedUsers(frame);
				} catch (IOException e) {
					e.printStackTrace();
				}
				
        	}else{
        		
        		String d[] = data.split("\\|",3);
        		String from = d[0];
        		String to = d[1];
        		String message = d[2];
        		
        		System.out.println("Array: " + java.util.Arrays.toString(d));
        		
                for (ChatWebSocket member : _members){
                	if( !member.getName().equals(from) && (to.equals("") || to.equals(member.getName())) ){
	                	try{
	                		System.out.println("Sending data");
	                        member._outbound.sendMessage(frame,message);
	                    }catch(IOException e) {Log.warn(e);}
                	}
                }
        	}

        }

        public void onDisconnect()
        {
        	//SendConnectedUsers();
            _members.remove(this);
        }
        
        public String getName(){
        	return _name;
        }
        
        private void SendConnectedUsers(byte frame){
        	System.out.println("Sending connected users");
        	
        	StringBuilder sb = new StringBuilder();
        	sb.append("{\"type\" : \"usersList\" , \"list\":[\"\"");
        	for (ChatWebSocket member : _members){
        		sb.append(",\"" +  member.getName() + "\"");
        	}
        	sb.append("] } ");
        	
        	String names = sb.toString();
        	
        	System.out.println(names);
        	
			for (ChatWebSocket member : _members){
				try{
					member._outbound.sendMessage(names);
					//member._outbound.sendMessage(frame, names);
				}catch(IOException e) {Log.warn(e);}
			}
        }
        
    }
	
}
